package com.study.common.utils;

import cn.hutool.core.exceptions.ExceptionUtil;
import sun.misc.BASE64Decoder;

import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @description: 自定义RSA公匙，私匙
 * @author: LChuang
 * @date: 2023/11/15 14:40
 */
public class RSAEncryptUtil {

    public static RSAPublicKey getRSAPublicKeyByBase64(String base64s) {
        RSAPublicKey publicKey = null;
        try {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec((new BASE64Decoder()).decodeBuffer(String.valueOf(base64s)));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (Exception e) {
            ExceptionUtil.stacktraceToString(e);
        }
        return publicKey;
    }

    public static RSAPrivateKey getRSAPrivateKeyByBase64(String base64s) {
        RSAPrivateKey privateKey = null;
        try {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec((new BASE64Decoder()).decodeBuffer(base64s));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            ExceptionUtil.stacktraceToString(e);
        }
        return privateKey;
    }

}
